package com.daily.tools.handler;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 策略模式：将处理器注册到Spring容器
 *
 * @Author: Mali
 * @Date: 2019/9/19 15:23
 * @Version 1.0
 */
@Component
public class HandlerProcessor implements BeanFactoryPostProcessor {

    private static final String HANDLER_PACKAGE = "com.daily.tools.handler.handler";

    /**
     * 扫描@HandlerType，初始化HandlerContext，将其注册到Spring容器
     *
     * @param beanFactory bean工厂
     * @throws BeansException
     */
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        Map<String, Class> handlerMap = new HashMap<>(3);
        Set<Class<?>> classSet = ClassScanner.scan(HANDLER_PACKAGE, HandlerType.class);
        classSet.forEach(clazz -> {
            String type = clazz.getAnnotation(HandlerType.class).value();
            handlerMap.put(type, clazz);
        });
        HandlerContext handlerContext = new HandlerContext(handlerMap);
        beanFactory.registerSingleton(HandlerContext.class.getName(), handlerContext);
    }
}
